package com.seaside.park.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seaside.common.bean.Result;
import com.seaside.park.bean.Rule;
import com.seaside.park.mapper.RuleMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "语音播报规则管理")
@RestController
@RequestMapping("/api/rule")
public class RuleAPI {

    @Autowired
    RuleMapper RuleMapper;

    @ApiOperation(value = "保存/修改语音播报规则", response = Result.class)
    @PostMapping("/save")
    public Result save(@RequestBody VoiceBroadcastRule voiceBroadcastRule) {
        List<String> areas = voiceBroadcastRule.getAreas();
        Rule rule = new Rule();
        rule.setAreaName(voiceBroadcastRule.getAreaName());
        rule.setId(voiceBroadcastRule.getId());
        rule.setType(voiceBroadcastRule.getType());
        rule.setStreamInfoId(voiceBroadcastRule.getStreamInfoId());
        StringBuilder areaBuilder = new StringBuilder();
        for(int i = 0; i < areas.size(); i++){
            if (i > 0) {
                areaBuilder.append("|");
            }
            areaBuilder.append(areas.get(i));
        }
        rule.setArea(areaBuilder.toString());
        if (rule.getId() == 0) {
            RuleMapper.insert(rule);
        } else {
            RuleMapper.updateById(rule);
        }
        return Result.OK("保存成功！", null);
    }

    @ApiOperation(value = "根据ID删除语音播报规则", response = Result.class)
    @PostMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        Rule rule = RuleMapper.selectById(id);
        if (rule != null && rule.getId() > 0) {
            RuleMapper.deleteById(rule);
        }
        return Result.OK("删除成功！", null);
    }

    @ApiOperation(value = "查询所有语音播报信息", response = Result.class)
    @GetMapping("/listAll")
    public Result listAll(@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
                          @RequestParam (value = "curSize", defaultValue = "10") Integer curSize) {
        Page<Rule> page = new Page<>(curPage, curSize);
        IPage<Rule> iPage = RuleMapper.selectPage(page, new QueryWrapper<Rule>().orderByDesc("id"));
        return Result.OK("查询成功", iPage);
    }

    @Data
    public static class VoiceBroadcastRule {
        private int id;
        private int streamInfoId;
        private String areaName;
        private String type;
        private List<String> areas;
    }
}
